import { RouteRecordRaw } from "vue-router";
import { defineStore } from "pinia";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import { listRoutes } from "@/api/menu";
// import menuMock from "../../views";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");
const WORKBENCH = import.meta.env.VITE_APP_WORKBENCH;

// setup
export const usePermissionStore = defineStore("permission", () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);
  // state 路由类型
  const routeType = useStorage("routeType", "", sessionStorage);
  // state 菜单id
  const menuId = useStorage("menuId", "menuId", sessionStorage);

  const showLeftMenu = ref(false);

  // actions
  function setShowLeftMenu() {
    showLeftMenu.value = true;
  }

  function setRoutes(newRoutes: RouteRecordRaw[]) {
    routes.value = constantRoutes.concat(newRoutes);
  }
  // 设置路由类型
  function setRouteType(type: string) {
    routeType.value = type;
  }
  // 设置菜单id
  function setMenuId(id: string) {
    menuId.value = id;
  }
  /**
   * 递归过滤有权限的异步(动态)路由
   *
   * @param routes 接口返回的异步(动态)路由
   * @param roles 用户角色集合
   * @returns 返回用户有权限的异步(动态)路由
   */
  let permissionCode = "";
  function filterAsyncRoutes(
    routes: RouteRecordRaw[],
    roles: string[],
    type: string,
    url?: string
  ) {
    const asyncRoutes: RouteRecordRaw[] = [];

    routes.forEach((route: any) => {
      const tmpRoute: any = {}; // ES6扩展运算符复制新对象
      const path = route.url;
      tmpRoute.enabled = route.enabled ?? 1;
      tmpRoute.name = path.replaceAll("/", "").toUpperCase();
      tmpRoute.path = route.permissionType === 3 ? `${path}` : `/${path}`;
      tmpRoute.componentUrl =
        route.permissionType === 3 ? `${path}` : `/${path}`;
      // 判断用户(角色)是否有该路由的访问权限
      if (!url) {
        permissionCode = route.permissionCode;
        // 主目录且为菜单，自动添加children
        if (route.permissionType === 1 || route.permissionType === 3) {
          tmpRoute.component = Layout;
          tmpRoute.redirect = `/${path}`;
          tmpRoute.path = "/";
          tmpRoute.name = "";
          route.children = [
            {
              url: route.url || "",
              permissionName: route.permissionName || "",
              icon: route.icon || "",
              name: path?.replaceAll("/", "").toUpperCase() || "",
              permissionType: route.permissionType,
              enabled: route.enabled ?? 1,
            },
          ];
        } else {
          tmpRoute.component = Layout;
        }
      } else {
        const component =
          modules[`../../views${tmpRoute.componentUrl}/index.vue`];
        if (component || route.permissionType === 0) {
          tmpRoute.component = component;
        } else {
          tmpRoute.component = modules[`../../views/error-page/404.vue`];
        }
      }

      // 定义meta数据
      tmpRoute.meta = {
        title: route.permissionName,
        icon: route.icon,
        keepAlive: true,
        hidden: route.showType === 2 ? true : false,
        applicationType: permissionCode || type,
        id: route.id,
        isJump: route.pageTarget ?? "0",
        permissionType: route.permissionType,
      };

      // 递归处理
      if (route.children && route.children?.length) {
        tmpRoute.children = filterAsyncRoutes(
          route.children,
          roles,
          type,
          tmpRoute.componentUrl
        );
      }

      asyncRoutes.push(tmpRoute);
    });

    return asyncRoutes;
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      // 接口获取所有路由,参数为空
      const type = "";
      listRoutes(type)
        .then(({ data: asyncRoutes }) => {
          setMenuId(Date.now().toString());
          // 根据角色获取有访问权限的路由
          // asyncRoutes = menuMock;
          sessionStorage.setItem("menu", JSON.stringify(asyncRoutes));
          const accessedRoutes = filterAsyncRoutes(
            asyncRoutes,
            ["admin"],
            type
          );
          setRoutes(accessedRoutes);
          resolve(accessedRoutes);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 混合模式左侧菜单
   */
  const mixLeftMenu = ref<RouteRecordRaw[]>([]);
  function getMixLeftMenu(activeTop: string) {
    routes.value.forEach((item) => {
      if (item.path === activeTop) {
        mixLeftMenu.value = item.children || [];
      }
    });
  }
  return {
    routes,
    setRoutes,
    generateRoutes,
    getMixLeftMenu,
    mixLeftMenu,
    routeType,
    setRouteType,
    filterAsyncRoutes,
    menuId,
    setMenuId,
    showLeftMenu,
    setShowLeftMenu,
  };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
